window.onload(() => {
  const streamVideoBox = getD("cDiv_stream")
  const streamVideo = getD('stream')
  const playVideo = getD('play');
  let chunk;
  const download = getD('downloadat');
  let recorder;
  let mediaStream;
  console.log("getD('start') ===> ", getD('start'))
  getD('start').addEventListener('click', start);
  getD('end').addEventListener('click', end);
  // document.getElementById('play-video').addEventListener('click', play);

  // MediaRecorder 测试
  const constraints = {
    audio: false,
    video: true,
  };

  function start() {
    console.log('navigator==> ', navigator)
    navigator.mediaDevices.getUserMedia(constraints)
      .then(stream => {
        mediaStream = stream;
        streamVideo.srcObject = stream;
        streamVideo.play();
        recorder = new MediaRecorder(stream);
        recorder.ondataavailable = e => {
          chunk = e.data;
          // download.href = URL.createObjectURL(chunk);
          console.log('URL.createObjectURL(chunk) ===> ', URL.createObjectURL(chunk))
        };
        recorder.start();
        toggle(streamVideoBox, 'flex')
      })
  }

  function end() {
    toggle(streamVideoBox, 'none')
    streamVideo.pause();
    recorder.stop();
    mediaStream.getTracks().forEach(track => {
      track.stop();
    });
  }

  function play() {
    playVideo.src = URL.createObjectURL(chunk);
    playVideo.play();
  }

  function getD(n) {
    return document.getElementById(n)
  }

  function toggle(dom, state) {
    dom.style.display = state
  }
})